<script setup lang="ts">
import { Divider, Modal } from 'ant-design-vue'
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import type { PaginationProps, TableProps } from 'ant-design-vue'
import type { ColumnsType } from 'ant-design-vue/es/table'
import { useRouter } from 'vue-router'
import { type RegistrationItem, getRegistrationsApi, updateRegistrationApi } from '~/api/common/login'

interface TableRow {
  key: number
  name: string
  sex: string
  libf: string
  subject: string
  examType: string
  examTime: string
  emial: string
  subject_code: string
  registerDate: string
  registrationStatus: number
  invoiceStatus: {
    text: string
    type: 'not-issued' | 'processing' | 'issued' | 'failed' | 'none'
    color: string
  }
}

const columns = shallowRef([
  { title: '报名时间', dataIndex: 'examTime', align: 'center', width: 180,
  },
  { title: '考试科目', align: 'center', dataIndex: 'libf', width: 480 },
  { title: '考试费用', align: 'center', dataIndex: 'fee', customRender: (opt: { text: string | number }) => `${opt?.text ?? ''} 元`, width: 140,
  },
  { title: '缴费状态', dataIndex: 'subject', align: 'center', width: 190 },
  { title: '发票状态', dataIndex: 'invoiceStatus', align: 'center', width: 190 },
  { title: '操作', align: 'center', dataIndex: 'action', width: 230,
  },
])
const loading = shallowRef(false)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef<TableRow[]>([])

const tableSize = ref<string[]>(['large'])

const open = ref(false)
const router = useRouter()
const formModel = reactive({
  subject: '',
  examType: '',
})

const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
// 报名成功的状态：4, 5, 6
const successStatusSet = new Set([4, 5, 6])

function isSuccessStatus(status?: number) {
  return typeof status === 'number' && successStatusSet.has(status)
}

function getInvoiceStatusInfo(item: RegistrationItem & { invoice_status?: number | null }) { 
  const registrationStatus = item.registration_status
  
  // 状态 0: 信息待完善 - 无发票
  if (registrationStatus === 0)
    return { text: '--', type: 'none' as const, color: '#8c8c8c' }
  
  // 状态 1: 待缴费 - 无发票
  if (registrationStatus === 1)
    return { text: '--', type: 'none' as const, color: '#8c8c8c' }
  
  // 状态 2: 缴费待审核 - 未申请发票
  if (registrationStatus === 2)
    return { text: '--', type: 'none' as const, color: '#8c8c8c' }
  
  // 状态 3: 缴费待审核（已申请开发票）- 等待处理
  if (registrationStatus === 3)
    return { text: '等待处理', type: 'processing' as const, color: '#faad14' }
  
  // 状态 4: 已经缴费成功（不申请发票）- 无发票
  if (registrationStatus === 4)
    return { text: '--', type: 'none' as const, color: '#8c8c8c' }
  
  // 状态 5: 已经缴费成功（申请发票 发票审核中状态）- 等待处理
  if (registrationStatus === 5)
    return { text: '等待处理', type: 'processing' as const, color: '#faad14' }
  
  // 状态 6: 已经缴费成功（申请发票 发票已经开的状态）- 已开票
  if (registrationStatus === 6)
    return { text: '已开票', type: 'issued' as const, color: '#52c41a' }
  
  // 状态 7: 缴费审核拒绝（未申请开发票状态）- 无发票
  if (registrationStatus === 7)
    return { text: '--', type: 'none' as const, color: '#8c8c8c' }
  
  // 状态 8: 缴费审核被拒绝（已申请开发票状态 发票未开票失败）- 开票失败
  if (registrationStatus === 8)
    return { text: '开票失败', type: 'failed' as const, color: '#ff4d4f' }
  
  // 默认情况
  return { text: '--', type: 'none' as const, color: '#8c8c8c' }
}

function getSubjectColor(subject?: string) {
  if (!subject)
    return '#376d9b'
  if (subject === '考试不合格' || subject === '已缴费待审核')
    return 'gray'
  if (subject === '缴费失败')
    return '#ff4d4f'
  if (subject === '报名成功')
    return '#376d9b'
  return '#376d9b'
}
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getRegistrationsApi()
    const items: RegistrationItem[] = Array.isArray(data) ? data : []
    const mapped: TableRow[] = items.map((it) => {
      const date = new Date(it.registration_time)
      const year = Number.isNaN(date.getTime()) ? '' : `${date.getFullYear()}年`
      const format = (date) => {
        if (!date)
          return '' // 处理空值
        const d = new Date(date) // 确保是Date对象（兼容时间戳、字符串等）
        const year = d.getFullYear()
        const month = String(d.getMonth() + 1).padStart(2, '0') // 月份从0开始，补0
        const day = String(d.getDate()).padStart(2, '0') // 日期补0
        return `${year}-${month}-${day}`
      }
      // 根据8个状态定义显示报名状态
      const subjectText = it.registration_status === 0
        ? '信息待完善'
        : it.registration_status === 1
          ? '待缴费'
          : it.registration_status === 2
            ? '已缴费待审核'
            : it.registration_status === 3
              ? '已缴费待审核'
              : it.registration_status === 4
                ? '报名成功'
                : it.registration_status === 5
                  ? '报名成功'
                  : it.registration_status === 6
                    ? '报名成功'
                    : it.registration_status === 7
                      ? '缴费失败'
                      : it.registration_status === 8
                        ? '缴费失败'
                        : '--'
      
      // 处理补考模式
      const makeupUnit = (it as any).makeup_unit
      let subjectName = (it.exam_subject as any).description || ''
      let fee = (it.exam_subject as any).exam_fee
      
      if (makeupUnit) {
        // 解析 makeup_unit，可能是字符串 "[1]" 或 "[1,2]" 或数组
        let makeupUnits: number[] = []
        try {
          if (typeof makeupUnit === 'string') {
            makeupUnits = JSON.parse(makeupUnit)
          } else if (Array.isArray(makeupUnit)) {
            makeupUnits = makeupUnit
          }
        } catch {
          // 如果解析失败，尝试直接使用
          makeupUnits = Array.isArray(makeupUnit) ? makeupUnit : []
        }
        
        // 如果 makeup_unit 存在且有效，处理补考逻辑
        if (makeupUnits.length > 0) {
          // 移除科目名称最后4个字符，然后加上"补考报名"
          if (subjectName && subjectName.length >= 4) {
            subjectName = subjectName.slice(0, -4) + '补考报名'
          } else {
            subjectName = subjectName + '补考报名'
          }
          
          // 根据选择的单元数量确定费用
          const examSubject = it.exam_subject as any
          if (makeupUnits.length === 2) {
            // 选择了两个单元 [1,2]
            fee = examSubject?.two_unit_fee || fee
          } else {
            // 只选择了一个单元 [1] 或 [2]
            fee = examSubject?.single_unit_fee || fee
          }
        }
      }
      
      const invoiceStatus = getInvoiceStatusInfo(it as any)
      // 根据8个状态定义显示操作按钮
      const action = it.registration_status === 0
        ? '继续报名'
        : it.registration_status === 1
          ? '缴费'
          : it.registration_status === 2
            ? '申请发票'
            : it.registration_status === 3
              ? '--' // 缴费待审核（已申请开发票），无操作按钮
              : it.registration_status === 4
                ? '申请发票'
                : it.registration_status === 5
                  ? '--' // 缴费成功（申请发票 发票审核中），无操作按钮
                  : it.registration_status === 6
                    ? '--' // 缴费成功（申请发票 发票已开），无操作按钮
                    : it.registration_status === 7
                      ? '--' // 缴费审核拒绝（未申请开发票），无操作按钮
                      : it.registration_status === 8
                        ? '--' // 缴费审核被拒绝（已申请开发票），无操作按钮
                        : '--'
      return {
        key: it.id,
        name: it.username,
        sex: '',
        subject_code: (it as any).subject_code || ((it as any).exam_subject && (it as any).exam_subject.subject_code) || '',
        libf: subjectName,
        fee,
        subject: subjectText,
        action,
        examType: year,
        examTime: format(date),
        emial: it.email,
        registerDate: format(date),
        registrationStatus: it.registration_status,
        invoiceStatus,
      }
    })
    let list = mapped
    if (formModel.subject) {
      list = list.filter(item => item.libf === formModel.subject)
    }
    if (formModel.examType) {
      list = list.filter(item => item.examType === formModel.examType)
    }
    dataSource.value = list
    pagination.total = mapped.length
  }
  finally {
    loading.value = false
  }
}

async function onSearch() {
  pagination.current = 1
  await init()
}

// 用户点击取消报名
async function handleCancel(record: TableRow) {
  Modal.confirm({
    title: '提示',
    content: '确定取消本次报名吗？',
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      try {
        const resp = await updateRegistrationApi({
          id: record.key,
          registration_status: 6,
        }) // 无需 as any，TypeScript 会自动推断类型
        if (resp?.code === 0) { // 假设后端用 code=0 或 success=true 表示成功
          Modal.success({
            title: '提示',
            content: '本次报名已取消。',
            centered: true,
            onOk: () => {
              init()
            },
          })
        }
        else {
          Modal.info({
            title: '提示',
            content: resp?.message || '取消失败，请稍后重试',
            centered: true,
          })
        }
      }
      catch (e) {
        Modal.info({
          title: '提示',
          content: '网络异常，取消失败，请稍后重试',
          centered: true,
        })
      }
    },
  })
}

function handlePay(record: TableRow) {
  if ((record as any)?.action === '继续报名') {
    const subjectCode = (record.subject_code || '').toUpperCase()
    const path = subjectCode.includes('RESIT')
      ? '/form/makeupregistrationform'
      : '/form/regrationform'
    router.push({ path, query: { registrationId: String(record.key) } })
  }
  else if ((record as any)?.action === '缴费') {
    router.push({ path: '/pages/innovice', query: { orderId: String(record.key) } })
  }
  else if ((record as any)?.action === '申请发票') {
    router.push({ path: '/pages/payment', query: { orderId: String(record.key) } })
  }
}

// 查看详情
function handledetail(record: TableRow) {
  // 跳转到报名详情页，携带 orderId（与缴费页一致的参数命名，后端详情接口已兼容）
  router.push({ path: '/myexamlist/detail', query: { orderId: String(record.key) } })
}

// 无编辑操作

// 已移除审核按钮逻辑

/**
 * 新增事件
 *
 */
function handleOk() {
  open.value = false
  Modal.destroyAll()
  onSearch()
}

/**
 * 密度切换
 *
 */

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

/**
 * 全选/反选事件
 *
 */

watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)

onMounted(() => {
  init()
})

// 预留展开开关，当前未使用
// const expand = ref(false)

// 表格主题风格切换
const tableTheme = ref<'theme-minimal' | 'theme-zebra' | 'theme-card' | 'theme-bordered'>('theme-minimal')
</script>

<template>
  <div :loading="loading">
      <a-breadcrumb style="font-size: 16px;">
        <a-breadcrumb-item>考试报名</a-breadcrumb-item>
        <a-breadcrumb-item>我的报名</a-breadcrumb-item>
      </a-breadcrumb>
    <div :loading="loading">
      <div class='profile-hero'>
      <span
        style="
     font-size:18px;
     color:gray;
     position: relative;
     top:-5px;
     "
      >
        我的报名
      </span>
      <div class="subject-header">
        <div class="subject-title" />
        <Divider class="subject-divider" size="small" />
      </div>

      <!-- 表格风格切换 -->
      <div
        style="display:none;"
        class="table-theme-switch"
      >
        <a-radio-group v-model:value="tableTheme" button-style="solid" size="small">
          <a-radio-button value="theme-minimal">
            简约
          </a-radio-button>
          <a-radio-button value="theme-zebra">
            斑马
          </a-radio-button>
          <a-radio-button value="theme-card">
            卡片
          </a-radio-button>
          <a-radio-button value="theme-bordered">
            边框
          </a-radio-button>
        </a-radio-group>
      </div>

      <a-table
        :loading="loading"
        :columns="filterColumns as ColumnsType<any>"
        :data-source="dataSource"
        :pagination="(dataSource && dataSource.length >= 10) ? pagination : false"
        :size="tableSize[0] as TableProps['size']"
        row-key="key"
        style="margin-bottom: 14px;"
        class="ccpit-exam-table theme-bordered common-font"
      >
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'libf'">
            <span
              class="exam-subject-link"
              @click="handledetail(scope?.record as TableRow)"
            >
              {{ scope?.record?.libf }}
            </span>
          </template>
          <template v-else-if="scope?.column?.dataIndex === 'subject'">
            <span
              style="padding: 2px 8px; border-radius: 3px;"
              :style="{ color: getSubjectColor(scope?.record?.subject) }"
            >
              <CheckCircleOutlined
                v-if="isSuccessStatus(scope?.record?.registrationStatus)"
                style="margin-right: 6px; color: #52c41a;"
              />
              {{ scope?.record?.subject }}
            </span>
          </template>
          <template v-else-if="scope?.column?.dataIndex === 'invoiceStatus'">
            <span
              class="invoice-status-pill"
              :style="{ color: scope?.record?.invoiceStatus?.color }"
            >
              <CheckCircleOutlined
                v-if="scope?.record?.invoiceStatus?.type === 'issued'"
                style="margin-right: 6px; color: #52c41a;"
              />
              <CloseCircleOutlined
                v-else-if="scope?.record?.invoiceStatus?.type === 'failed'"
                style="margin-right: 6px; color: #ff4d4f;"
              />
              {{ scope?.record?.invoiceStatus?.text }}
            </span>
          </template>
          <template v-else-if="scope?.column?.dataIndex === 'action'">
            <a-space v-if="scope?.record?.registrationStatus === 0 || scope?.record?.registrationStatus === 1 || scope?.record?.registrationStatus === 2 || scope?.record?.registrationStatus === 4">
              <button
                style="display: none;"
                size="middle" class="btn-ccpit btn-ccpit-primary"
                @click="handleCancel(scope?.record as TableRow)"
              >
                <span
                  style="
              position: relative;
              top:-3px;
              "
                >
                  取消报名
                </span>
              </button>
              <button
                class="btn-ccpit-payment"
                @click="handlePay(scope?.record as TableRow)"
              >
                <span>
                  {{ scope?.record?.action }}
                </span>
              </button>
              <button
                class="btn-ccpit-detail"
                @click="handledetail(scope?.record as TableRow)"
              >
                <span>
                  查看详情
                </span>
              </button>
            </a-space>
            <span v-else>
              <a-space>
                <button
                  style="display: none;"
                  size="middle" class="btn-ccpit-payment"
                  @click="handleCancel(scope?.record as TableRow)"
                >
                  <span
                    style="
              position: relative;
              "
                  >
                    取消报名
                  </span>
                </button>

                <button
                  size="middle" class="btn-ccpit-detail"
                  @click="handledetail(scope?.record as TableRow)"
                >
                  <span>
                    查看详情
                  </span>
                </button>
              </a-space>

            </span>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal v-model:open="open" title="新建规则" width="400px" @ok="handleOk">
      <a-space direction="vertical" size="large" class="w-full">
        <a-input placeholder="请输入" />
        <a-textarea placeholder="请输入" />
      </a-space>
    </a-modal>
    </div>
  </div>
</template>

<style lang="less" scoped>
@import './index.scss';
.subject-wrapper {
  background-color: #ffffff;
  padding: 24px 28px 32px;
  margin-bottom: 120px;
  position: relative;
  top: -20px;
  height: 87vh;
  border-radius: 5px;
  box-shadow: 0 12px 30px -18px rgba(0, 0, 0, 0.35);
}
div::-webkit-scrollbar {
  width: 3px; /* 滚动条宽度 */
}
div::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1); /* 半透明黑色，你可以根据需要调整透明度 */
  border-radius: 4px; /* 滑块圆角 */
}
.subject-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 14px;
}
.subject-title {
  font-size: 22px;
  font-weight: 600;
  color: #1f2937;
}
.subject-divider {
  margin: 0;
  flex: 1;
}
.subject-card {
  background: #fff;
  border-radius: 14px;
  margin:10px 10px;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 24px 45px -22px rgba(42, 84, 156, 0.35);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.subject-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 28px 50px -20px rgba(42, 84, 156, 0.45);
}
.subject-cover {
  position: relative;
  height: 160px;
  background-size: cover;
  background-position: center;
}
.subject-status {
  position: absolute;
  top: 14px;
  left: 14px;
  padding: 4px 12px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 500;
  color: #fff;
  background: rgba(0, 0, 0, 0.45);
  backdrop-filter: blur(4px);
}
.subject-body {
  padding: 20px 20px 18px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  height: calc(100% - 160px);
}
.subject-name {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.4;
}
.subject-meta {
  font-size: 13px;
  color: #6b7280;
  display: flex;
  align-items: center;
  gap: 8px;
}
.meta-dot {
  font-size: 8px;
  color: #9ca3af;
}
.subject-desc {
  font-size: 13px;
  color: #4b5563;
  line-height: 1.55;
  min-height: 42px;
}
.subject-footer {
  margin-top: auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.subject-action {
  font-size: 13px;
  color: #2563eb;
}
.subject-footer :deep(.ant-btn) {
  border-radius: 999px;
  padding: 0 16px;
  height: 30px;
}
.subject-status.tag-primary {
  background: linear-gradient(135deg, #2563eb 0%, #3b82f6 100%);
}
.subject-status.tag-orange {
  background: linear-gradient(135deg, #f97316 0%, #fb923c 100%);
}
.subject-status.tag-blue {
  background: linear-gradient(135deg, #0ea5e9 0%, #38bdf8 100%);
}
.subject-status.tag-green {
  background: linear-gradient(135deg, #22c55e 0%, #4ade80 100%);
}
.subject-status.tag-red {
  background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);
}
.subject-status.tag-gray {
  background: rgba(149, 158, 172, 0.78);
}
@media (max-width: 768px) {
  .subject-wrapper {
    padding: 16px;
  }
  .subject-body {
    padding: 16px;
  }
}

/* 表格风格主题 */
.table-theme-switch {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

/* 通用表格基础优化 */
.ccpit-exam-table :deep(.ant-table) {
  border-radius: 10px;
  overflow: hidden;
  background: #ffffff;
}
.ccpit-exam-table :deep(.ant-table-tbody > tr > td),
.ccpit-exam-table :deep(.ant-table-thead > tr > th) {
  transition: background-color 0.2s ease, color 0.2s ease, box-shadow 0.2s ease;
}

/* 放大表格文字（标题与内容） */
.ccpit-exam-table :deep(.ant-table-thead > tr > th),
.ccpit-exam-table :deep(.ant-table-tbody > tr > td) {
  font-size: 17px;
}

/* 1) 简约风格 */
.ccpit-exam-table.theme-minimal :deep(.ant-table-thead > tr > th) {
  background: #f8fafc;
  color: #334155;
  font-weight: 600;
  border-bottom: 1px solid #e2e8f0;
}
.ccpit-exam-table.theme-minimal :deep(.ant-table-tbody > tr > td) {
  background: #ffffff;
  border-bottom: 1px solid #f1f5f9;
  padding: 14px 16px;
}
.ccpit-exam-table.theme-minimal :deep(.ant-table-tbody > tr:hover > td) {
  background: #f1f5f9;
}

/* 2) 斑马条纹 */
.ccpit-exam-table.theme-zebra :deep(.ant-table-thead > tr > th) {
  background: #f3f4f6;
  color: #374151;
  font-weight: 600;
  border-bottom: 1px solid #e5e7eb;
}
.ccpit-exam-table.theme-zebra :deep(.ant-table-tbody > tr:nth-child(odd) > td) {
  background: #fafafa;
}
.ccpit-exam-table.theme-zebra :deep(.ant-table-tbody > tr:nth-child(even) > td) {
  background: #ffffff;
}
.ccpit-exam-table.theme-zebra :deep(.ant-table-tbody > tr:hover > td) {
  background: #eef2ff;
}

/* 3) 卡片风格（更强的圆角与阴影） */
.ccpit-exam-table.theme-card {
  box-shadow: 0 14px 32px -18px rgba(42, 84, 156, 0.35);
  border-radius: 12px;
}
.ccpit-exam-table.theme-card :deep(.ant-table) {
  border-radius: 12px;
  overflow: hidden;
}
.ccpit-exam-table.theme-card :deep(.ant-table-thead > tr > th) {
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
  color: #1f2937;
  font-weight: 700;
  border-bottom: 1px solid #e5e7eb;
}
.ccpit-exam-table.theme-card :deep(.ant-table-tbody > tr > td) {
  background: #ffffff;
  border-bottom: 1px solid #f1f5f9;
}
.ccpit-exam-table.theme-card :deep(.ant-table-tbody > tr:hover > td) {
  background: #f8fafc;
  box-shadow: inset 0 0 0 1px #e5e7eb;
}

/* 4) 明确边框风格（紧凑/商用） */
.ccpit-exam-table.theme-bordered :deep(.ant-table) {
  border: 1px solid #e5e7eb;
}
.ccpit-exam-table.theme-bordered :deep(.ant-table-thead > tr > th) {
  background: #f9fafb;
  color: #111827;
  font-weight: 600;
  border-right: 1px solid #e5e7eb;
}
.ccpit-exam-table.theme-bordered :deep(.ant-table-tbody > tr > td) {
  border-right: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
  padding: 10px 14px;
}
.ccpit-exam-table.theme-bordered :deep(.ant-table-tbody > tr:hover > td) {
  background: #f3f4f6;
}
.ccpit-exam-table.theme-bordered :deep(.ant-table-tbody > tr:last-child > td) {
  border-bottom: none;
}

/* 考试科目链接样式 */
.exam-subject-link {
  color: #376d9b;
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-block;
}

.exam-subject-link:hover {
  text-decoration: underline;
  color: #2a5a8a;
}
.profile-hero{
    overflow-y: scroll;
  height: 89vh;
  padding: 15px 10px;
  padding-bottom: 80px;
  margin-bottom: 40px;
}

@media (max-height: 800px) {
  .profile-hero {
    height: calc(100vh - 100px);
    padding-bottom: 60px;
    margin-bottom: 30px;
  }
}
</style>
